package goods

import (
	"context"
	"go_final/mxshop_api/goods_web/api"
	"go_final/mxshop_api/goods_web/forms"
	"go_final/mxshop_api/goods_web/global"
	goodspb "go_final/mxshop_api/goods_web/proto/protofile"
	"net/http"
	"strconv"

	sentinel "github.com/alibaba/sentinel-golang/api"
	"github.com/alibaba/sentinel-golang/core/base"

	"go.uber.org/zap"

	"github.com/gin-gonic/gin"
)

// List 商品列表
func List(c *gin.Context) {
	req := goodspb.GoodsFilterRequest{}

	priceMin := c.DefaultQuery("pmin", "0")
	priceMinInt, _ := strconv.Atoi(priceMin)
	req.PriceMin = int32(priceMinInt)

	priceMax := c.DefaultQuery("pmax", "0")
	priceMaxInt, _ := strconv.Atoi(priceMax)
	req.PriceMax = int32(priceMaxInt)

	isHot := c.DefaultQuery("ih", "0")
	if isHot == "1" {
		req.IsHot = true
	}

	isNew := c.DefaultQuery("in", "0")
	if isNew == "1" {
		req.IsNew = true
	}

	isTab := c.DefaultQuery("it", "0")
	if isTab == "1" {
		req.IsTab = true
	}

	categoryID := c.DefaultQuery("c", "0")
	categoryIDInt, _ := strconv.Atoi(categoryID)
	req.TopCategory = int32(categoryIDInt)

	pages := c.DefaultQuery("p", "0")
	pagesInt, _ := strconv.Atoi(pages)
	req.Pages = int32(pagesInt)

	perNum := c.DefaultQuery("pnum", "0")
	perNumInt, _ := strconv.Atoi(perNum)
	req.PagePerNums = int32(perNumInt)

	keywords := c.DefaultQuery("q", "")
	req.KeyWords = keywords

	brand := c.DefaultQuery("b", "0")
	brandInt, _ := strconv.Atoi(brand)
	req.Brand = int32(brandInt)

	// 请求商品服务
	e, block := sentinel.Entry("good-list", sentinel.WithTrafficType(base.Inbound))
	if block != nil {
		c.JSON(http.StatusTooManyRequests, gin.H{
			"msg": "操作过于频繁",
		})
	}
	res, err := global.GoodsClient.GoodsList(context.Background(), &req)
	if err != nil {
		zap.S().Info("[List] 查询 【商品列表】失败", err.Error())
		api.HandleGrpcError2Http(err, c)
		return
	}
	e.Exit()

	c.JSON(http.StatusOK, res)
}

// New 新建商品
func New(c *gin.Context) {
	goodsForm := forms.GoodsForm{}
	err := c.ShouldBind(&goodsForm)

	if err != nil {
		api.HandleValidateError(c, err)
		return
	}

	res, err := global.GoodsClient.CreateGoods(context.Background(), &goodspb.CreateGoodsInfo{
		Name:            goodsForm.Name,
		GoodsSn:         goodsForm.GoodsSn,
		Stocks:          goodsForm.Stocks,
		MarketPrice:     goodsForm.MarketPrice,
		ShopPrice:       goodsForm.ShopPrice,
		GoodsBrief:      goodsForm.GoodsBrief,
		ShipFree:        *goodsForm.ShipFree,
		Images:          goodsForm.Images,
		DescImages:      goodsForm.DescImages,
		GoodsFrontImage: goodsForm.FrontImage,
		CategoryId:      goodsForm.CategoryId,
		BrandId:         goodsForm.Brand,
	})

	if err != nil {
		zap.S().Info("创建商品失败", err)
		api.HandleGrpcError2Http(err, c)
		return
	}

	// TODO 调用库存服务设置商品的库存
	c.JSON(http.StatusOK, res)
}

func Detail(c *gin.Context) {
	goodsID := c.Param("id")
	goodsIDInt, _ := strconv.Atoi(goodsID)
	// goodsIDInt, _ := strconv.ParseInt(goodsID, 10, 32) // 10进制, 32位

	res, err := global.GoodsClient.GetGoodsDetail(context.Background(), &goodspb.GoodInfoRequest{
		Id: int32(goodsIDInt),
	})

	if err != nil {
		api.HandleGrpcError2Http(err, c)
		return
	}

	// TODO 调用库存服务查询商品的库存并返回给前端
	c.JSON(http.StatusOK, res)
}

func Delete(c *gin.Context) {
	goodsID := c.Param("id")
	goodsIDInt, _ := strconv.Atoi(goodsID)

	res, err := global.GoodsClient.DeleteGoods(context.Background(), &goodspb.DeleteGoodsInfo{
		Id: int32(goodsIDInt),
	})

	if err != nil {
		api.HandleGrpcError2Http(err, c)
		return
	}

	c.JSON(http.StatusOK, res)
}

func Update(c *gin.Context) {
	goodsForm := forms.GoodsForm{}
	err := c.ShouldBind(&goodsForm)

	if err != nil {
		api.HandleValidateError(c, err)
		return
	}

	goodsID := c.Param("id")
	goodsIDInt, _ := strconv.Atoi(goodsID)
	res, err := global.GoodsClient.UpdateGoods(context.Background(), &goodspb.CreateGoodsInfo{
		Id:              int32(goodsIDInt),
		Name:            "",
		GoodsSn:         "",
		Stocks:          0,
		MarketPrice:     0,
		ShopPrice:       0,
		GoodsBrief:      "",
		ShipFree:        false,
		Images:          nil,
		DescImages:      nil,
		GoodsFrontImage: "",
		CategoryId:      0,
		BrandId:         0,
	})

	if err != nil {
		api.HandleGrpcError2Http(err, c)
		return
	}

	c.JSON(http.StatusOK, res)
}

func UpdateStatus(c *gin.Context) {
	goodsStatusForm := forms.GoodsStatusForm{}

	err := c.ShouldBind(&goodsStatusForm)
	if err != nil {
		api.HandleValidateError(c, err)
		return
	}

	goodsID := c.Param("id")
	goodsIDInt, _ := strconv.Atoi(goodsID)
	res, err := global.GoodsClient.UpdateGoods(context.Background(), &goodspb.CreateGoodsInfo{
		Id:     int32(goodsIDInt),
		IsNew:  *goodsStatusForm.IsNew,
		IsHot:  *goodsStatusForm.IsHot,
		OnSale: *goodsStatusForm.OnSale,
	})

	if err != nil {
		api.HandleGrpcError2Http(err, c)
		return
	}

	c.JSON(http.StatusOK, res)
}

// Stocks 调用库存服务获取商品的库存
func Stocks(ctx *gin.Context) {
	id := ctx.Param("id")
	_, err := strconv.ParseInt(id, 10, 32)
	if err != nil {
		ctx.Status(http.StatusNotFound)
		return
	}

	//TODO 商品的库存
	return
}
